//
//  VC2ViewController.m
//  PCAForWar
//
//  Created by dllo on 16/1/22.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "VC2ViewController.h"
#import "CellForVC2.h"
#import "ModelForVC2.h"
#import <MJRefresh.h>
#import "VC2ForCell.h"
#import <DKNightVersion.h>
#import "NetWorkingHandler.h"

#define WIDTH  self.view.frame.size.width
#define HEIGHT  self.view.frame.size.height
@interface VC2ViewController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSString *strForShangLa;
@property (nonatomic, assign) NSInteger pageForShangLa;
@property (nonatomic, retain) CellForVC2 *cellVC2;
@property (nonatomic, retain) UIButton *buttonTop;

@end

@implementation VC2ViewController

- (void)dealloc{
    
    _tableView.dataSource = nil;
    _tableView.delegate = nil;
    
    [_cellVC2 release];
    [_tableView release];
    [_arrForJunPing release];
    [_strForShangLa release];
    [_buttonTop release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.arrForJunPing= [NSMutableArray array];
    
    self.strForShangLa = @"page=1&type=5&processID=getNewsList&pageSize=20&";
    
    // 设置默认的页数为第一页
    self.pageForShangLa = 1;
    
    [self handleData];
    
    [self createNavigation];
    [self createTableVIew];
    [self createButtonForTop];
    
    // 调用下拉刷新
    [self header];
    // 调用上拉刷新
    [self shangLa];
}

#pragma mark 夜间模式
- (void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorWithColors([UIColor redColor], [UIColor colorWithRed:39 / 256.f green:39 / 256.f blue:39 / 256.f alpha:1]);
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        
    } else {
        
        [DKNightVersionManager dawnComing];
    }
    
    self.tableView.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:52 / 256.f green:52 / 256.f blue:52 / 256.f alpha:1]);
    
}

#pragma mark  解析数据
- (void)handleData {
    
    [NetWorkingHandler handleDataByStr:@"http://admin.militaryapp.china.com/News/NewsServlet.do" body:self.strForShangLa header:@"application/x-www-form-urlencoded; charset=UTF-8" block:^(id result) {
        
        NSArray *arrDown = [result objectForKey:@"data"];
        
        // 判断  如果没有数据了  不会crash
        if ([arrDown.class isSubclassOfClass:[NSMutableArray class]]) {
            
            for (NSDictionary *dic in arrDown) {
                
                ModelForVC2 *model = [[ModelForVC2 alloc] init];
                
                [model setValuesForKeysWithDictionary:dic];
                
                [self.arrForJunPing addObject:model];
                
                [self.tableView reloadData];
                
                [self.tableView.mj_footer endRefreshing];
            }
            
        }
        
    }];
    
}

#pragma mark  创建NavigationController
- (void)createNavigation {
    
    self.navigationItem.title = @"军评";
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor],NSFontAttributeName : [UIFont fontWithName:@"AmericanTypewriter-Bold" size:22],}];
    
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    
}

#pragma mark 创建tableView
- (void)createTableVIew {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    
    [self.view addSubview:self.tableView];
    
    // 取消横线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.tableView registerClass:[CellForVC2 class] forCellReuseIdentifier:@"pool1"];
    
    
    [_tableView release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.arrForJunPing.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 判断出现TopButton
    if (indexPath.row == 30) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showButton3" object:nil];
    }
    
    if (indexPath.row == 15) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"hiddenButton3" object:nil];
    }
    
    CellForVC2 *cell = [tableView dequeueReusableCellWithIdentifier:@"pool1"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    ModelForVC2 *model = [self.arrForJunPing objectAtIndex:indexPath.row];
    
    [cell passModel:model];
    
    // 夜间模式改变颜色
    cell.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:52 / 256.f green:52 / 256.f blue:52 / 256.f alpha:1]);
    
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 100;
    
}

#pragma mark 点击Cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    VC2ForCell *vc2Cell = [[VC2ForCell alloc] init];
    
    self.hidesBottomBarWhenPushed = YES;
    
    ModelForVC2 *model = [self.arrForJunPing objectAtIndex:indexPath.row];
    
    vc2Cell.Location = model.NewsUrl;
    vc2Cell.Title = model.Title;
    vc2Cell.NewsSummary = model.NewsSummary;
    vc2Cell.NewsUrl = model.NewsUrl;
    vc2Cell.NewsCommentNum = model.NewsCommentNum;
    
    [self.navigationController pushViewController:vc2Cell animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
    
    [vc2Cell release];
}

#pragma mark 下拉刷新
- (void)header {
    
    self.strForShangLa = @"page=1&type=5&processID=getNewsList&pageSize=20&";
    
    self.pageForShangLa = 1;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewAction)];
    
    [self.tableView.mj_header beginRefreshing];
    
}

- (void)loadNewAction {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.tableView.mj_header endRefreshing];
        
        [self.tableView reloadData];
        
    });
}

#pragma mark 上拉刷新
- (void)shangLa {
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        self.strForShangLa = [NSString stringWithFormat:@"page=%ld&type=5&processID=getNewsList&pageSize=20&", ++self.pageForShangLa];
        
        [self handleData];
        
    }];
    
    self.tableView.mj_footer = footer;
}

#pragma mark 创建Top button
- (void)createButtonForTop {
    
    self.buttonTop = [UIButton buttonWithType:UIButtonTypeSystem];
    
    self.buttonTop.frame = CGRectMake(self.tableView.frame.size.width - 60, self.tableView.frame.size.width + 20, 30, 30);
    
    [self.view addSubview:self.buttonTop];
    
    [self.buttonTop setImage:[UIImage imageNamed:@"Dingbu"] forState:UIControlStateNormal];
    
    self.buttonTop.hidden = YES;
    
    [self.buttonTop addTarget:self action:@selector(TopAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 通知判断出现
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleShowButton) name:@"showButton3" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleButtonclick) name:@"hiddenButton3" object:nil];
}

- (void)handleButtonclick {
    
    self.buttonTop.hidden = YES;
    
}
- (void)handleShowButton {
    
    self.buttonTop.hidden = NO;
    
}

- (void)TopAction:(UIButton *)button {
    
    self.buttonTop.hidden = YES;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition: UITableViewScrollPositionTop animated:YES];
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
